<%@ page language="java" contentType="text/html; charset=utf-8" %>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page"/>
<jsp:useBean id="bb" class="weaver.general.BaseBean"/>
<%@ page import="cn.hutool.core.util.RandomUtil" %>
<%@ page import="cn.hutool.http.ContentType" %>
<%@ page import="cn.hutool.http.HttpRequest" %>
<%@ page import="cn.hutool.http.HttpResponse" %>
<%@ page import="cn.hutool.http.HttpUtil" %>
<%@ page import="cn.hutool.json.JSONUtil" %>
<%@ page import="com.alibaba.fastjson.JSON" %>
<%@ page import="com.alibaba.fastjson.JSONArray" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="com.alibaba.fastjson.serializer.SerializerFeature" %>
<%@ page import="com.google.common.base.Joiner" %>
<%@ page import="org.apache.commons.codec.digest.DigestUtils" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="java.math.BigDecimal" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.TreeMap" %>
<%
    JSONObject jsonData = new JSONObject();
    String name = Util.null2String(request.getParameter("name"));
    String amount = Util.null2String(request.getParameter("amount"));
    amount = fMultiply(amount, "100");
    bb.writeLog(">>>>>withdrawal>>>>name=" + name+",amount="+amount);
    String custId = Util.null2String(queryCustomer(name));
    String walletBal = queryBalancer(custId);
    bb.writeLog(">>>>>withdrawal>>>>custId=" + custId+",walletBal="+walletBal);
    String msg ="";
    if (fCompare(walletBal, amount) >= 0) {
        bb.writeLog("个人余额足够扣款");
        HashMap<Object, Object> bodyMap = new HashMap<>(2);
        bodyMap.put("custId", custId);
        bodyMap.put("drawAmount", amount);
        bodyMap.put("remark", "餐卡充值");
        msg = Util.null2String(withdrawal(bodyMap));
    } else {
        if (fCompare(walletBal, "0") > 0) {
            bb.writeLog("个人余额不够扣款");
            HashMap<Object, Object> bodyMap = new HashMap<>(2);
            bodyMap.put("custId", custId);
            bodyMap.put("drawAmount", walletBal);
            bodyMap.put("remark", "餐卡充值");
            msg = Util.null2String(withdrawal(bodyMap));
            String balance = fSubtract(amount, walletBal);
            System.out.println("balance=" + balance);
            HashMap<Object, Object> bodyMap1 = new HashMap<>(2);
            bodyMap1.put("custId", custId);
            bodyMap1.put("subsidyDrawAmount", balance);
            bodyMap1.put("remark", "餐卡充值");
            msg = Util.null2String(withdrawal(bodyMap1));
        } else {
            bb.writeLog("补贴余额足够扣款");
            HashMap<Object, Object> bodyMap = new HashMap<>(2);
            bodyMap.put("custId", custId);
            bodyMap.put("subsidyDrawAmount", amount);
            bodyMap.put("remark", "餐卡充值");
            msg = Util.null2String(withdrawal(bodyMap));
        }

    }
    jsonData.put("msg", msg);
    out.print(jsonData.toJSONString());
%>
<%!
    public static String withdrawal(HashMap<Object, Object> bodyMap) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog(">>>>>withdrawal>>>>bodyMap=" + bodyMap);
        String url = "https://api.xnzn.net/tengyun-api/leopen/account/withdrawal";
        String resultStr = Util.null2String(invokeHandle(url, bodyMap));
        baseBean.writeLog(">>>>>withdrawal>>>>resultStr=" + resultStr);
        String message = "";
        if (!"".equals(resultStr)) {
            JSONObject resultJson = JSONObject.parseObject(resultStr);
            String code = Util.null2String(resultJson.getString("code"));
            if ("10000".equals(code)) {
                message = "乐牛钱包扣款成功";
            } else {
                message = Util.null2String(resultJson.getString("msg"));
            }
        }
        return message;
    }
   //查询钱包余额
    private static String queryBalancer(String custId) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog(">>>>>queryBalancer>>>>custId=" + custId);
        String url = "https://api.xnzn.net/tengyun-api/leopen/account/balance/query";
        HashMap<Object, Object> bodyMap = new HashMap<>(2);
        bodyMap.put("custId", custId);
        String resultStr = Util.null2String(invokeHandle(url, bodyMap));
        baseBean.writeLog(">>>>>queryBalancer>>>>resultStr=" + resultStr);
        String walletBal = "0.00";
        if (!"".equals(resultStr)) {
            JSONObject resultJson = JSONObject.parseObject(resultStr);
            String code = Util.null2String(resultJson.getString("code"));
            if ("10000".equals(code)) {
                String dataStr = Util.null2String(resultJson.getString("data"));
                JSONObject dataJson = JSONObject.parseObject(dataStr);
                walletBal = Util.null2String(dataJson.getString("walletBal"));
            }
        }
        return walletBal;
    }
    //查询员工卡号
    private static String queryCustomer(String custNum) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog(">>>>>queryCustomer>>>>custNum=" + custNum);
        String url = "https://api.xnzn.net/tengyun-api/leopen/customer/query";
        HashMap<Object, Object> bodyMap = new HashMap<>(2);
        bodyMap.put("custNum", custNum);
        String resultStr = Util.null2String(invokeHandle(url, bodyMap));
        baseBean.writeLog(">>>>>queryCustomer>>>>resultStr=" + resultStr);
        String custId = "";
        if (!"".equals(resultStr)) {
            JSONObject resultJson = JSONObject.parseObject(resultStr);
            String code = Util.null2String(resultJson.getString("code"));
            if ("10000".equals(code)) {
                String dataStr = Util.null2String(resultJson.getString("data"));
                JSONObject dataJson = JSONObject.parseObject(dataStr);
                JSONArray dataList = JSONArray.parseArray(dataJson.getString("customerList"));
                if (dataList.size() > 0) {
                    for (int i = 0; i < dataList.size(); i++) {
                        custId = dataList.getJSONObject(i).getString("custId");
                    }
                }
            }
        }

        return custId;
    }
    //接口处理器
    private static String invokeHandle(String url, HashMap<Object, Object> bodyMap) {
        /**
         * appid          应用ID（平台提供）
         * appsecret      应用秘钥（平台提供）
         * version        版本号，默认1.0.0
         * signtype       加密方法，md5 / sha256
         * timestamp      当前时间戳
         * nonce          随机数，不小于10位
         * content        请求内容
         * sign           加签字符串
         */
        String result = "";
        BaseBean baseBean = new BaseBean();
        //应用秘钥
        String appsecret = "ecda26d1add24442b1d5a7af44b7c850";
        //请求内容字典排序，转换为String
        String content = JSON.toJSONString(bodyMap, SerializerFeature.MapSortField, SerializerFeature.WriteMapNullValue);
       try{
           Map<String, Object> map = new TreeMap<>();
           map.put("appid", "190633894444294144");
           map.put("version", "1.0.0");
           map.put("signtype", "md5");
           map.put("timestamp", String.valueOf(System.currentTimeMillis()));
           map.put("nonce", RandomUtil.randomNumbers(10));
           map.put("content", content);
           //生成sign，防篡改
           String toSignStr = Joiner.on("&")
                   .useForNull("")
                   .withKeyValueSeparator("=")
                   .join(map) + "&appsecret=" + appsecret;
           // md5/sha256 加签（其他方式待提供）
           String sign = DigestUtils.md5Hex(toSignStr).toUpperCase();
           map.put("sign", sign);
           //post请求
           map.replace("content", bodyMap);
           baseBean.writeLog("post url：\n" + url);
           //查询组织信息
           HttpRequest request = HttpUtil.createPost(url);
           baseBean.writeLog("request：\n" + JSONUtil.toJsonStr(map));
           request.body(JSONUtil.toJsonStr(map), ContentType.JSON.toString());
           HttpResponse response = request.execute();
           baseBean.writeLog("response：\n" + response.body());
           result = response.body();
       }catch (Exception e){
           e.printStackTrace();
       }//构造请求验签参数

        return result;
    }

    // 乘法保留两位小数
    public static String fMultiply(String a, String b) {
        a = isZero(a);
        b = isZero(b);
        BigDecimal bg1 = new BigDecimal(a);
        BigDecimal bg2 = new BigDecimal(b);
        BigDecimal bd = bg1.multiply(bg2).setScale(0, BigDecimal.ROUND_HALF_UP);
        return bd.toString();
    }
    // 大小比较 -1 0 1
    public static int fCompare(String a, String b) {
        a = isZero(a);
        b = isZero(b);
        BigDecimal bg1 = new BigDecimal(a);
        BigDecimal bg2 = new BigDecimal(b);

        return bg1.compareTo(bg2);
    }
    //零判断
    public static String isZero(String a) {
        if ("".equals(a)) {
            a = "0";
        }
        return a;
    }
    // f点型相减
    public static String fSubtract(String a, String b) {
        a = isZero(a);
        b = isZero(b);
        BigDecimal bg1 = new BigDecimal(a);
        BigDecimal bg2 = new BigDecimal(b);
        BigDecimal bd = bg1.subtract(bg2).setScale(0, BigDecimal.ROUND_HALF_UP);
        return bd.toString();
    }
%>